<template>
  <cu-layout tabbar="/pages/main/home" :bgStyle="{ src: $CDN('/common/static/images/main_bg.png') }" :showNavar="true">
    <!-- 骨架屏 -->
    <!-- <cu-skeleton :loading="!pageDataInitFinished" v-if="!pageDataInitFinished"> </cu-skeleton> -->

    <!-- 顶部状态栏 -->
    <template #navbar>
      <HeaderNavbar :opacity="opacityVal" />
    </template>

    <!-- 内容区域 -->
    <view :class="[`${prefixCls}-home-container`]">
      <view style="margin: 0 32rpx">
        <Search v-model="searchkeyword" />
      </view>
      <!-- 轮播 -->
      <view class="swiper-container">
        <swiper class="swiper" circular :indicator-dots="true" indicator-color="#ffffff80" indicator-active-color="#FFFFFF" :autoplay="true" :interval="5000" :duration="500">
          <swiper-item v-for="(item, index) in banner_list" :key="index">
            <view class="swiper-item" @click="handleJump(item)">
              <image :src="item.cover" />
            </view>
          </swiper-item>
        </swiper>
      </view>
      <!-- 找房单，秒杀，积分，老带新 -->
      <view class="container" v-if="mallDataList && mallDataList.length">
        <view class="project-item" v-for="(item, index) in mallDataList" :key="index" @click="handleMall(item)">
          <image :src="item.icon_image" />
          <text>{{ item.icon_name }}</text>
        </view>
        <view class="mall-second-line" v-if="secondDataList && secondDataList.length > 0">
          <view class="second-mall-item" v-for="(item, index) in secondDataList" :key="item.id" @click="handleMall(item)">
            <template v-if="item.icon_image">
              <image class="pic-item" :src="item.icon_image"></image>
              <text>{{ item.icon_name }}</text>
            </template>
          </view>
        </view>
      </view>
      <!-- 热门门店 -->
      <!-- <view class="hot-resources"> <view class="card-name">热门门店</view></view> -->
      <!-- 推荐户型 -->
      <view class="housing-resources">
        <view class="card-name">热门房源</view>
        <template v-if="projectPages.dataList.length == 0">
          <cu-empty mode="data" :style="{ flex: projectPages.dataList.length == 0 ? '1' : '' }" :text="projectPages.status == 'loading' ? '正在加载' : '没有合适房源'"> </cu-empty>
        </template>
        <template v-else>
          <view class="housing-item" :class="[{ 'even-column': index % 2 !== 0 }]" v-for="(item, index) in projectPages.dataList" :key="index" @click="handleDetail(item)">
            <image class="image-icon" :src="item.cover"></image>
            <!-- <image class="mark-vr"></image> -->
            <image v-if="item.video_cover" class="mark-video" :src="$CDN('/common/static/images/ic_bofang@3x.png')"></image>
            <image class="mark-tag" :src="$CDN('/common/static/images/hot-icon@3x.png')"></image>
            <view class="mark-address">
              <image class="address" :src="$CDN('/common/static/images/ic_map.png')"></image>
              <text>{{ item.business_district }}</text>
            </view>
            <view class="room-type">{{ item.room_type_name }}</view>
            <text class="tag-item" v-for="(items, indexs) in item.show_tag" :key="indexs">{{ items }}</text>
            <view v-if="item.minArea" class="desc">{{ item.minArea }}m²起</view>
            <view class="price">
              <text v-if="item.minPrice">{{ item.minPrice }} <text class="unit">元/间/月起</text></text>
            </view>
          </view>
          <uv-load-more :status="projectPages.status" :dashed="true" :line="true" marginTop="20px" />
        </template>
      </view>
    </view>
  </cu-layout>
</template>

<script>
import { getConfig, getFilterTags, homeParlour, recommendRoomType } from '@/api/home'
import share from '@/mixins/share'
import { mapGetters } from 'vuex'
import HeaderNavbar from './components/header-navbar'
import listBlock from './components/list-block'
import Search from './components/search'
import searchList from './components/search-list'

export default {
  name: 'home',
  mixins: [share],
  components: { Search, listBlock, searchList, HeaderNavbar },
  data() {
    return {
      pageDataInitFinished: false,
      opacityVal: 0,
      searchkeyword: '',

      onShareAppMessage: {
        title: '',
        path: '',
      },
      banner_list: [], // 轮播图数据
      mallDataList: [], // 金刚位
      secondDataList: [], // 金刚位第二排
      isScroll: true,
      list: [
        { title: '全部区域', key: 'business_district', options: [], value: {}, icon: 1 },
        { title: '离我最近', key: 'rate', icon: 0, value: '' },
        { title: '价格排序', key: 'price', icon: 0, value: '' },
        { title: '房源筛选', key: 'districts', options: [], value: [], icon: 1 },
      ],
      search_tag_list: [], // 商圈标签
      tabActiveList: [],
      projectPages: {
        status: 'loadmore',
        tags: [],
        latitude: '',
        longitude: '',
        orderBy: 'distance:asc',
        minPrice: '',
        // orderBy: 'showMinPrice:asc',
        business_district: '',
        districts: '',
        page: 1,
        length: 10,
        dataList: [],
      },
    }
  },
  watch: {
    'cityConfig.cityId'(nv) {
      // console.log('🚀 ~ nv:home', nv)
      this.getData()
    },
  },
  // 计算属性
  computed: {
    ...mapGetters(['token', 'cityConfig', 'locationInfo', 'userInfo']),
  },
  filters: {},
  onLoad(options) {
    // #ifdef MP
    // 小程序识别二维码
    if (options.scene) {
      const sceneParams = decodeURIComponent(options.scene).split('=')
      options[sceneParams[0]] = sceneParams[1]
    }
    // #endif

    // 加载首页请求 TODO
    setTimeout(() => {
      this.pageDataInitFinished = true
    }, 1e3)

    // 解析分享信息
    if (options.spm) {
      this.$Platform.share.decryptSpm(options.spm)
    }

    // 进入指定页面(完整页面路径)
    if (options.page) {
      this.$ROUTE.go(decodeURIComponent(options.page))
    }
    // 获取搜索栏需要定位到头部的高度

    this.getData()
  },
  onReady() {},
  onShow() {},
  onHide() {},
  // 下拉刷新
  onPullDownRefresh() {},
  // 加载更多
  onReachBottom() {
    if (this.projectPages.total != this.projectPages.dataList.length) {
      this.projectPages.page++
      // 获取项目数据
      this.projectList()
    }
  },
  // 页面滚动
  onPageScroll(e) {
    // console.log('home', e)
    const top = e.scrollTop
    this.opacityVal = top > this.$Platform.navbar ? 1 : top * 0.01
  },
  options: {
    styleIsolation: 'shared',
  },
  methods: {
    // 获取页面数据
    async getData() {
      const { cityId } = this.cityConfig
      if (cityId) {
        this.projectPages.page = 1
        this.projectPages.dataList = []
        // 获取搜索条件数据
        this.getFilterTags()
        // 获取轮播图和 获取金刚位
        this.projectTop()
        // 获取金刚位
        this.getConfig()
        // 获取项目数据
        this.projectList()
      }
    },
    async getFilterTags() {
      const { cityId } = this.cityConfig
      const { data } = await getFilterTags({ cityId })
      const { filter, options, search_tag_list, priceList } = data
      this.search_tag_list = search_tag_list.sort((a, b) => {
        return a.sort - b.sort
      })
      this.list[3].options = filter.map((v) => {
        v.value = []
        return v
      })
      const ojb = {
        name: 'price',
        title: '租金预算',
        list: priceList,
        value: [],
      }
      this.list[3].options.unshift(ojb)
      this.list[0].options = options.filter((item) => {
        if (item.name === '商圈' || item.name === '地铁') {
          item.children = item.children.map((v) => {
            v.id = v.id || v.name
            v.field = v.id ? v.id : v.name
            return v
          })
        }
        return item.name != '公司'
      })
      // 过滤掉通勤找房
    },
    async projectTop() {
      const { cityId } = this.cityConfig
      const { data } = await homeParlour({ cityId, plat: this.$Platform.os, recommend: 0 })
      const Banner = data.find((v) => {
        return v.type == 'Banner'
      })
      const TopNav = data.find((v) => {
        return v.type == 'TopNav'
      })
      this.banner_list = Banner?.list
      // this.mallDataList = TopNav?.list
      // const { banner_list, search_tag_list } = data
      // this.banner_list = banner_list
      // const list = [...this.search_tag_list, ...search_tag_list]
      // let uniqueArray = list.filter((obj, index, self) => index === self.findIndex((t) => t.tag_value === obj.tag_value))
      // this.search_tag_list = uniqueArray.sort((a, b) => {
      //   return a.sort - b.sort
      // })
    },
    async getConfig() {
      const { cityId } = this.cityConfig
      const { data } = await getConfig({ cityId })
      this.mallDataList = data.filter((item) => item.line == 1)
      this.secondDataList = data.filter((item) => item.line == 2)
    },
    isChinese(str) {
      // 匹配中文字符的正则表达式
      const reg = /[\u4e00-\u9fa5]/
      return reg.test(str)
    },
    changeAreaData({ value }) {
      if (!value) return
      const map = { districts: [], business_district: [], subway: [] }
      value.forEach((v) => {
        if (this.isChinese(v.fieldKey)) {
          if (v.key && v.key.length) {
            map.business_district = [...map.business_district, ...v.key]
          } else {
            map.districts.push(v.fieldKey)
          }
        } else if (v.key && v.key.length) {
          map.subway.push(v.key)
        } else {
          map.subway.push(v.fieldKey)
        }
      })
      return map
    },
    async projectList() {
      const { cityId } = this.cityConfig
      const { page, length } = this.projectPages
      this.projectPages.status = 'loading'
      const { data } = await recommendRoomType({ length, page, recommend: 0, cityId })
      const { recordsList, recordsTotal } = data
      this.projectPages.total = recordsTotal
      this.projectPages.dataList = [...this.projectPages.dataList, ...recordsList]
      if (recordsTotal == this.projectPages.dataList.length) {
        this.projectPages.status = 'nomore'
      } else {
        this.projectPages.status = 'loadmore'
      }
    },
    handleDetail({ project_id: projectId, room_type_id: id }) {
      // const type = video_cover ? 'v2' : 'v10'
      this.$ROUTE.go('/pages/subpackage/housing-resources/room-detail/index', { projectId, id, type: 'v10' })
    },
    handleMall({ type, jump_url, jump_type, icon_name }) {
      if (jump_url === '') return uni.$uv.toast('功能暂未开放，敬请期待!')
      this.$ROUTE.go({ path: jump_url })
      // if (!jump_url) return uni.$uv.toast('功能暂未开放，敬请期待!')
      // if (jump_type == 'BoyuMini') {
      //   if (jump_url === '?') return uni.$uv.toast('功能暂未开放，敬请期待!')
      //   this.$ROUTE.go({ path: jump_url })
      // } else if (jump_type == 'PageLink') {
      //   this.$ROUTE.go(jump_url)
      // } else if (jump_type == 'ThirdMini') {
      //   uni.navigateToMiniProgram({
      //     appId: appid,
      //     path: jump_url,
      //   })
      // }
      // this.$ROUTE.go({ path: jump_url })
    },
    handleJump({ type, jump_type, jump_url, appid, mini_path }) {
      if (jump_type == 'BoyuMini') {
        this.$ROUTE.go({ path: mini_path })
      } else if (jump_type == 'PageLink') {
        this.$ROUTE.go(jump_url)
      } else if (jump_type == 'ThirdMini') {
        uni.navigateToMiniProgram({
          appId: appid,
          path: mini_path,
          // extraData: {
          //   data1: '',
          // },
        })
      } else {
        this.$ROUTE.go({ path: jump_url })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .uv-navbar {
  .uv-navbar__content {
    justify-content: flex-start;
  }
}
.#{prefixCls('home-container')} {
  position: relative;
  padding: 20rpx 0rpx;
  // $uv-primary
  .swiper-container {
    width: 100%;
    box-sizing: border-box;
    padding: 24rpx 32rpx;
    border-radius: 16rpx;
    .swiper {
      height: 128px;
      .swiper-item,
      image,
      image {
        width: 100%;
        height: 100%;
        border-radius: 16rpx;
      }
    }
  }
  .container {
    width: calc(100% - 64rpx);
    margin: 0 16px 22rpx;
    box-sizing: border-box;
    padding: 24rpx 0rpx 0;
    border-radius: 16rpx;
    background: white;
    display: flex;
    flex-wrap: wrap;

    .project-item {
      width: 25%;
      display: flex;
      align-items: center;
      flex-direction: column;
      margin-bottom: 15px;
      image,
      image {
        width: 84rpx;
        height: 84rpx;
        margin-bottom: 8rpx;
      }
      text {
        font-weight: 400;
        font-size: 12px;
        color: #333333;
        line-height: 20px;
      }
    }
  }

  .scroll-view {
    background: white;
  }
  .tag-list {
    width: max-content;
    min-width: 100%;
    background: #ffffff;
    display: flex;
    padding: 4px 16px 16px;
    .tag-item {
      font-size: 12px;

      font-weight: 400;
      color: #666666;
      padding: 6px 16px;
      border: 1px solid #eeeeee;
      border-radius: 34px;
      margin-right: 8px;
    }
    .tag-active {
      color: $uv-primary;
      border-color: $uv-primary;
    }
  }
  .housing-resources {
    padding-bottom: 80px;
    margin-top: 24rpx;
    background: white;
    background-size: auto 200px;
    background-repeat: no-repeat;
    padding-left: 32rpx;
    padding-right: 32rpx;
    overflow: auto;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    .card-name {
      flex-basis: 100%;
      margin: 16px 0;

      font-weight: 600;
      font-size: 16px;
      color: #333333;
    }
    .housing-item {
      width: calc(50% - 8rpx);
      margin-bottom: 36rpx;
      margin-left: 8rpx;
      box-sizing: border-box;
      position: relative;
      .image-icon {
        width: 336rpx;
        height: 252rpx;
        background: #f1f1f1;
        border-radius: 16rpx;
        position: relative;
        &::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, #000000 100%);
          pointer-events: none; /* 确保点击不会被遮挡 */
          opacity: 0.1;
        }
      }
      .mark-vr {
        width: 36rpx;
        height: 36rpx;
        position: absolute;
      }
      .mark-video {
        width: 36rpx;
        height: 36rpx;
        position: absolute;
        top: 16rpx;
        left: 16rpx;
      }
      .mark-tag {
        position: absolute;
        width: 40rpx;
        height: 24rpx;
        left: 296rpx;
      }
      .mark-address {
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 20rpx;
        color: #ffffff;
        line-height: 24rpx;
        position: absolute;
        left: 16rpx;
        top: 212rpx;
        // mix-blend-mode: difference;
        .address {
          width: 20rpx;
          height: 20rpx;
          margin-right: 10rpx;
        }
      }
      .room-type {
        margin: 20rx 0 16rpx;

        font-weight: 600;
        font-size: 24rpx;
        color: #333333;
      }
      .tag-item {
        margin-right: 16rpx;
        padding: 2rpx 8rpx;
        font-weight: 400;
        font-size: 20rpx;
        color: #999999;
        line-height: 24rpx;
        background: #f5f5f5;
        border-radius: 4rpx;
        display: inline-block;
      }
      .desc {
        margin: 16rpx 0;
        font-weight: 400;
        font-size: 24rpx;
        color: #666666;
        line-height: 24rpx;
      }
      .price {
        color: $uv-price-primary;
        font-size: 30rpx;
        font-weight: bold;
        .unit {
          font-size: 20rpx;
          margin-left: 4rpx;
        }
      }
    }
    .even-column {
      padding-left: 12rpx;
      .mark-video {
        left: 28rpx;
      }
      .mark-address {
        left: 28rpx;
      }
    }
  }
  .mall-second-line {
    margin-bottom: 24rpx;
    display: flex;
    align-items: center;
    overflow: hidden;
    padding: 0 16rpx;
    .second-mall-item,
    .pic-item {
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      background-color: #fff;
      overflow: hidden;
      flex-shrink: 1;
      width: 218rpx;
      height: 84rpx;
      border-radius: 16rpx;
      image {
        width: 218rpx;
        height: 84rpx;
      }
      text {
        position: absolute;
        left: 16rpx;
        height: 40rpx;
        font-weight: 700;
        font-size: 24rpx;
        color: #002115;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
        text-transform: none;
      }
      &::after {
        display: none;
      }
    }
    .second-mall-item {
      position: relative;
      margin-right: 16rpx;
      &:last-child {
        margin-right: 0;
      }
    }
  }
}
</style>
